package com.xyz.gate.filter;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.xyz.gate.common.R;
import com.xyz.gate.service.UserService;
import com.xyz.gate.service.WhitelistUrl;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 进行登陆检查
 */
public class LoginCheckFilter extends ZuulFilter {

    @Resource
    UserService userService;


    @Resource
    WhitelistUrl whitelistUrl;

    /**
     * 是否应该执行该过滤器，如果是false，则不执行该filter
     */
    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        if(!ctx.sendZuulResponse()){
            return false;
        }
        return true;
    }

    /**
     * 过滤器类型
     * 顺序: pre ->routing -> post ,以上3个顺序出现异常时都可以触发error类型的filter
     */
    @Override
    public String filterType() {

        return FilterConstants.PRE_TYPE;
    }

    /**
     * 同filterType类型中，order值越大，优先级越低
     */
    @Override
    public int filterOrder() {

        return 900;
    }


    /**
     * 执行业务操作，可执行sql,nosql等业务
     */
    @Override
    public Object run() {


        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String requestURL = request.getRequestURL().toString();

        if (!whitelistUrl.isNeedLogin(request.getRequestURI())) {
            return null;
        }

        String authorization = request.getHeader("Authorization");
        JSONObject info = getUserNameAndPwd(authorization);
        if(userService.checkPwd(info)) {
            request.setAttribute("userName", info.getString("userName"));
            return null;
        }
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(401);
        ctx.getResponse().setCharacterEncoding("UTF-8");
        ctx.getResponse().setContentType("application/json");
        try {
            ctx.getResponse().getWriter().write(R.error("用户名或者密码错误！").toString());
        } catch (Exception e) {
        }
        return null;
    }

    private JSONObject getUserNameAndPwd (String authorization) {
        JSONObject info = new JSONObject();
        try {
            String decodeStr = StrUtil.removePrefix(authorization,"Basic").trim();
            decodeStr = Base64Decoder.decodeStr(decodeStr);

            String[] array = StrUtil.split(decodeStr,":");
            if(array.length==2) {
                info.put("userName",array[0]);
                info.put("passwd",array[1]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return info;
    }
}
